<template>
  <el-row :gutter="20">
    <el-col :span="11">
      <el-row class="query-top" :gutter="20">
        <el-col :span="8">
          <el-input v-model="name" />
        </el-col>
        <el-col :span="16">
          <el-button :icon="Search" type="primary" @click="queryMainTable()"> 查询 </el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-table
          ref="mainTableRef"
          v-loading="leftTableLoading"
          border
          :data="mainTable.data"
          highlight-current-row
          :max-height="mainTable.maxHeight"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" label="序号" type="index" width="55" />
          <el-table-column align="left" label="名称" prop="name" />
        </el-table>
        <el-pagination
          background
          :current-page="mainTable.queryForm.pageNum"
          :layout="mainTable.layout"
          :page-size="mainTable.queryForm.pageSize"
          :total="mainTable.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-row>
    </el-col>
    <el-col :span="11">
      <el-row class="query-top" :gutter="20">
        <el-col :span="8">
          <el-input v-model="subTable.queryForm.keyword" />
        </el-col>
        <el-col :span="16">
          <el-button :icon="Search" type="primary" @click="querySubTable"> 查询 </el-button>
          <el-button type="primary" @click="handleSave">确定移除</el-button>
        </el-col>
      </el-row>
      <el-table
        ref="subTableRef"
        border
        :data="subTable.data"
        highlight-current-row
        :max-height="mainTable.maxHeight"
        stripe
        @selection-change="handleSubSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" label="序号" type="index" width="55" />
        <el-table-column align="left" label="名称" prop="name" />
      </el-table>
    </el-col>
  </el-row>
</template>
<script setup>
import { getList, backTableHeight } from "@/api/mains";
import { Search } from "@element-plus/icons-vue";
const props = defineProps({
  approvers: {
    type: Array,
    default: () => []
  },
  approvalForm: {
    type: Number,
    default: () => {}
  }
});

const emit = defineEmits(["handle-select-appovals"]);

const groupUserUrl = "system/processUserGroup";
const userUrl = "user";
const multipleSection = ref([]);
const mainTableRef = ref(null);
const subTableRef = ref(null);
const name = ref("");
const leftTableLoading = ref(false);

const mainTable = reactive({
  data: [],
  total: 0,
  maxHeight: "",
  templateData: [],
  layout: "total, sizes, prev, pager, next",
  templeSetion: [],
  queryForm: {
    pageNum: 1,
    pageSize: 10
  }
});
const subTable = reactive({
  data: [],
  queryForm: {},
  maxHeight: "",
  templateData: [],
  subMultipleSection: [],
  subAllSection: [],
  subtempleSetion: []
});

mainTable.maxHeight = backTableHeight();
subTable.maxHeight = backTableHeight() + 100;

// 删除勾选掉的数据
const onDelSetion = (data, templateData, sectionData) => {
  const delData = templateData.filter(item => {
    return sectionData.every(cItem => item.id !== cItem.id);
  });
  const newData = [...data];
  newData.forEach(item => {
    const index = delData.findIndex(cItem => item.id === cItem.id);
    if (~index) {
      data.splice(index, 1);
    }
  });
};

//添加新勾选的数据
const onAddSetion = (data, templateData, sectionData) => {
  const addData = sectionData.filter(item => {
    return templateData.every(cItem => cItem.id !== item.id);
  });

  const newData = [...data];
  addData.forEach(item => {
    if (newData.every(cItem => cItem.id !== item.id)) {
      data.push(item);
    }
  });
};

const updateRenderSubTableData = isClose => {
  const data = [...props.approvers];
  //对新增数据删除数据的重复处理
  onDelSetion(data, mainTable.templeSetion, multipleSection.value);
  onAddSetion(data, mainTable.templeSetion, multipleSection.value);
  emit("handle-select-appovals", data, isClose);
};

const updateRenderSection = (data, ele, referenceData) => {
  nextTick(() => {
    data.forEach(row => {
      if (referenceData.some(cItem => row.id === cItem.id)) {
        ele.toggleRowSelection(row, true); //初始状态勾选
      }
    });
  });
};

const handleData = data => {
  const currentData = data.filter(item => {
    return props.approvers.some(cItem => {
      return item.id === cItem.id;
    });
  });

  //保留初始数据，以便搜索，原始数据还在
  mainTable.templateData = [...data];
  subTable.templateData = [...props.approvers];
  subTable.data = [...subTable.templateData];
  multipleSection.value = [...currentData];
  mainTable.templeSetion = [...currentData];
  updateRenderSection(data, mainTableRef.value, subTable.data); //对比数据，对数据重复做处理
};
const getUser = async () => {
  const { queryForm } = mainTable;
  leftTableLoading.value = true;
  const res = await getList(userUrl, {
    ...queryForm,
    ...{ username: name.value }
  });
  leftTableLoading.value = false;
  mainTable.total = res.data.total;
  mainTable.data = res.data.rows || [];
  mainTable.data = mainTable.data.map(item => {
    item.name = item.username;
    return item;
  });
  handleData(mainTable.data);
};
const getGroupUser = async () => {
  const { queryForm } = mainTable;
  leftTableLoading.value = true;
  const res = await getList(groupUserUrl, {
    ...queryForm,
    ...{ name: name.value }
  });
  leftTableLoading.value = false;
  mainTable.total = res.data.total;
  mainTable.data = res.data.rows || [];
  handleData(mainTable.data);
};

function initData() {
  if (props.approvalForm === 1) {
    getUser();
  } else {
    getGroupUser();
  }
}

const queryMainTable = () => {
  updateRenderSubTableData(false);
  initData();
};

const querySubTable = () => {
  const { templateData, queryForm, subAllSection } = subTable;
  if (!queryForm.keyword) {
    subTable.data = [...templateData];
  } else {
    subTable.data = templateData.filter(item => {
      return item.name.indexOf(queryForm.keyword) >= 0;
    });
  }

  subTable.subtempleSetion = subTable.data.filter(item => {
    return subAllSection.some(cItem => cItem.id === item.id);
  });
  updateRenderSection(subTable.data, subTableRef.value, subAllSection, true);
};

const handleSizeChange = val => {
  updateRenderSubTableData(false);
  mainTable.queryForm.pageSize = val;

  initData();
};
const handleCurrentChange = val => {
  updateRenderSubTableData(false);
  mainTable.queryForm.pageNum = val;

  initData();
};
const handleSave = () => {
  updateRenderSubTableData(true);
  initData();
};

const handleSelectionChange = val => {
  multipleSection.value = val;
};

const handleSubSelectionChange = val => {
  subTable.subMultipleSection = [...val];
  onDelSetion(subTable.subAllSection, subTable.subtempleSetion, subTable.subMultipleSection);
  onAddSetion(subTable.subAllSection, subTable.subtempleSetion, subTable.subMultipleSection);

  const newVal = [...multipleSection.value];
  val.forEach(item => {
    const index = newVal.findIndex(cItem => item.id === cItem.id);

    multipleSection.value.splice(index, 1);
  });
};
watch(
  () => props.approvalForm,
  () => {
    initData();
  },
  {
    immediate: true
  }
);

watch(
  () => props.approvers,
  () => {
    const currentData = mainTable.data.filter(item => {
      return props.approvers.some(cItem => item.id === cItem.id);
    });

    subTable.templateData = [...props.approvers];
    subTable.data = [...subTable.templateData];
    multipleSection.value = [...currentData];
    mainTable.templeSetion = [...currentData];
  },
  {
    deep: true
  }
);
</script>
<style lang="scss" scoped>
.query-top {
  margin-bottom: 20px;
}
</style>
